#include "systemactivationmainwindow.h"
#include "ui_systemactivationmainwindow.h"
#include <QHostInfo>
#include <QDebug>
#include "kwindowsystem.h"
#include <QTimer>
#include <KWindowSystem>
SystemActivationMainWindow::SystemActivationMainWindow(int argc, char *argv, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SystemActivationMainWindow)
{
    if(argc>1 && strcmp(argv,"-install")==0)
        return;

    ui->setupUi(this);
    ui->frame->setFrameShape(QFrame::NoFrame);
    this->setAttribute(Qt::WA_TranslucentBackground, false);
    this->setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);
    this->setWindowIcon(QIcon::fromTheme("kylin-activation"));
    this->setWindowModality(Qt::WindowModal);
    KWindowSystem::setState(this->winId(),NET::SkipTaskbar | NET::SkipPager);
    this->setWindowFlags(windowFlags() &~ Qt::WindowMaximizeButtonHint);

    gint dbus_init_flag = 0;
    dbus_init_flag = dbus_init();
    if(! dbus_init_flag)
    {
        QMessageBox::about(this, NULL, QString(tr("Dbus Error!")));
        exit_service();
        qApp->exit(0);
    }

    m_qrcodewid=new QrCodeActivationWidget;
    m_ukeyWid=new UkeyActivationWidget;
    m_importLicense=new ImportLicenseFileWidget;
    m_deactivateWid=new DeactivateWidget;
    m_secretKeyWid=new SecretKeyActivationWidget;
    m_activateSucceed = new ActivateSucceedWidget;
    if(argc>1 && strcmp(argv,"-auto")==0)
        m_deactivateWid->disconnect_any_signal();
    else if (argc==1)
        checkIfSupportCancel();

    deactivate_label = new KBorderlessButton(ui->widget_8);
    import_auth_file_label = new KBorderlessButton(ui->widget_8);
    deactivate_label->setVisible(false);
    deactivate_label->setText(tr("Deactivate"));
    import_auth_file_label->setText(tr("Modifying license file"));

    deacAndImporLayout = new QHBoxLayout;
    deacAndImporLayout ->setContentsMargins(0,0,0,0);
    deacAndImporLayout ->setSpacing(20);
    deacAndImporLayout ->addWidget(import_auth_file_label, 0,Qt::AlignCenter);
    deacAndImporLayout->addWidget(deactivate_label,0,Qt::AlignCenter);
    ui->widget_8->setLayout(deacAndImporLayout);

    connect(deactivate_label, &QPushButton::clicked, this, [=]{
        ui->frame->layout()->replaceWidget(ui->homepagewidget,m_deactivateWid);
        ui->homepagewidget->setParent(nullptr);
    });

    connect(import_auth_file_label, &QPushButton::clicked, this, [=]{
        ui->frame->layout()->replaceWidget(ui->homepagewidget,m_importLicense);
        m_importLicense->clearData();
        ui->homepagewidget->setParent(nullptr);
        m_importLicense->isSiteLicenseInterFace(false);
    });

    connect(m_qrcodewid,&QrCodeActivationWidget::returnSignal,this,[=]{
        ui->frame->layout()->replaceWidget(m_qrcodewid,ui->homepagewidget);
        m_qrcodewid->setParent(nullptr);
    });

    connect(m_qrcodewid,&QrCodeActivationWidget::activateSucceed,this,[=]{

        ui->frame->layout()->replaceWidget(m_qrcodewid,m_activateSucceed);
        m_qrcodewid->setParent(nullptr);
        m_activateSucceed->setParent(ui->frame);
    });

    connect(m_ukeyWid,&UkeyActivationWidget::returnSignal,this,[=]{
       ui->frame->layout()->replaceWidget(m_ukeyWid,ui->homepagewidget);
       m_ukeyWid->setParent(nullptr);
    });

    connect(m_ukeyWid,&UkeyActivationWidget::activateSucceed,this,[=]{
        ui->frame->layout()->replaceWidget(m_ukeyWid,m_activateSucceed);
        m_ukeyWid->setParent(nullptr);
        m_activateSucceed->setParent(ui->frame);
    });

    connect(m_importLicense,&ImportLicenseFileWidget::returnSignal,this,[=]{
       ui->frame->layout()->replaceWidget(m_importLicense,ui->homepagewidget);
       m_importLicense->setParent(nullptr);
//       if(license_check("/etc/LICENSE","/etc/.kyinfo")==0)
//       {
//           ui->pushButton->setEnabled(true);
//           ui->qrcodebtn->setEnabled(true);
//           ui->ukeybtn->setEnabled(true);
//           deactivate_label->setEnabled(true);
//       }
    });

    connect(m_importLicense, &ImportLicenseFileWidget::activateSucceed, this, [=]{
        ui->frame->layout()->replaceWidget(m_importLicense,m_activateSucceed);
        m_importLicense->setParent(nullptr);
        m_activateSucceed->setParent(ui->frame);
    });

    connect(m_deactivateWid,&DeactivateWidget::returnSignal,this,[=]
    {
       ui->frame->layout()->replaceWidget(m_deactivateWid,ui->homepagewidget);
       m_deactivateWid->setParent(nullptr);
    });

    connect(m_secretKeyWid,&SecretKeyActivationWidget::returnSignal,this,[=]{
       ui->frame->layout()->replaceWidget(m_secretKeyWid,ui->homepagewidget);
       m_secretKeyWid->setParent(nullptr);
    });

    connect(m_secretKeyWid,&SecretKeyActivationWidget::activateSucceed,this,[=]{
        ui->frame->layout()->replaceWidget(m_secretKeyWid,m_activateSucceed);
        m_secretKeyWid->setParent(nullptr);
        m_activateSucceed->setParent(ui->frame);
    });

    //激活信息上传
    m_kmsActivation = new activation_thread_kms();
    m_accessManager_Registered = new QNetworkAccessManager();
    connect(m_kmsActivation, SIGNAL(activation_post_signal(QString)),this, SLOT(send_activation_info(QString)));
    connect(this->m_accessManager_Registered, SIGNAL(finished(QNetworkReply*)),this, SLOT(finishedSlot_info(QNetworkReply*)));
    connect(m_kmsActivation, SIGNAL(activation_message_signal(int )),this, SLOT(activationMessageSlot(int )));
    connect(m_secretKeyWid,SIGNAL(activationMessageSignal(int)),this,SLOT(activationMessageSlot(int )));
    connect(m_qrcodewid,SIGNAL(activationMessageSignal(int)),this,SLOT(activationMessageSlot(int )));
    connect(m_ukeyWid,SIGNAL(activationMessageSignal(int)),this,SLOT(activationMessageSlot(int )));


    if(QGSettings::isSchemaInstalled(QString("org.ukui.control-center.personalise").toLocal8Bit()))
    {
        m_gsetting=new QGSettings(QString("org.ukui.control-center.personalise").toLocal8Bit());
        connect(m_gsetting,&QGSettings::changed,this,[=](const QString &key){
            if(key=="transparency")
                this->repaint();
        });
    }

    if(QGSettings::isSchemaInstalled(QString("org.ukui.style").toLocal8Bit()))
    {
        QGSettings* gsetting=new QGSettings(QString("org.ukui.style").toLocal8Bit(),QByteArray(),this);
        if(gsetting->keys().contains("styleName"))
        {
            if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
                ui->iconlabel->setPixmap(QPixmap(":/res/kylin-wihte.png"));
            else
                ui->iconlabel->setPixmap(QPixmap(":/res/kylin.png"));
            connect(gsetting,&QGSettings::changed,[=](const QString &key){
                if(key=="styleName")
                {
                    if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
                        ui->iconlabel->setPixmap(QPixmap(":/res/kylin-wihte.png"));
                    else
                        ui->iconlabel->setPixmap(QPixmap(":/res/kylin.png"));
                }

                if(key == "iconThemeName")
                {
                    this->setWindowIcon(QIcon::fromTheme("kylin-activation"));
                }

            });
        }
    }
    ui->qrcodebtn->setText(tr("Scan QR code to avtivate"), true);
}

SystemActivationMainWindow::~SystemActivationMainWindow()
{
    delete m_qrcodewid;
    delete m_ukeyWid;
    delete m_importLicense;
    delete m_deactivateWid;
    delete m_kmsActivation;
    delete m_secretKeyWid;
    delete m_activateSucceed;
    delete m_accessManager_Registered;
    delete ui;
}

void SystemActivationMainWindow::on_qrcodebtn_clicked()
{
    m_qrcodewid->checkIfOnline();

    ui->frame->layout()->replaceWidget(ui->homepagewidget,m_qrcodewid);
    ui->homepagewidget->setParent(nullptr);
    m_qrcodewid->setParent(ui->frame);
    m_qrcodewid->resetControlsState(1);
}

void SystemActivationMainWindow::on_ukeybtn_clicked()
{
    m_ukeyWid->setRemindLabelText();
    ui->frame->layout()->replaceWidget(ui->homepagewidget,m_ukeyWid);
    ui->homepagewidget->setParent(nullptr);
    m_ukeyWid->m_thread->start();
    m_ukeyWid->m_timer->start(100);
    m_ukeyWid->restartCheckUkey();
    m_ukeyWid->resetControlsState(0);
}

void SystemActivationMainWindow::on_authfileimportbtn_clicked()
{
    ui->frame->layout()->replaceWidget(ui->homepagewidget,m_importLicense);
    m_importLicense->clearData();
    ui->homepagewidget->setParent(nullptr);
    m_importLicense->isSiteLicenseInterFace(true);
}

void SystemActivationMainWindow::on_secretkeybtn_clicked()
{
//    m_secretKeyWid->resetControlsState(0);
    ui->frame->layout()->replaceWidget(ui->homepagewidget,m_secretKeyWid);
    m_secretKeyWid->clearData();
    ui->homepagewidget->setParent(nullptr);
}

//局域网自动激活
void SystemActivationMainWindow::activationMessageSlot(int activation)
{
    if (activation == 0)
    {
        m_kmsActivation->start();
        m_kmsActivation->wait();
    }

    exit_service();
}

void SystemActivationMainWindow::checkAuthorizationFile()
{
    QString lpath = "/etc/LICENSE";
    QString ipath = "/etc/.kyinfo";
    int ret = license_check(lpath.toLocal8Bit().data(), ipath.toLocal8Bit().data());
    if(ret!=0)
    {
        ui->frame->layout()->replaceWidget(ui->homepagewidget,m_importLicense);
        m_importLicense->clearData();
        ui->homepagewidget->setParent(nullptr);
        m_importLicense->isSiteLicenseInterFace(false);
        m_importLicense->checkLicense();
    }

}

void SystemActivationMainWindow::checkIfSupportCancel()
{
    int activationStatus = 0;
    activationStatus = status_code();
    if(activationStatus==1) {
        this->udpSocket = socketmanager::GetInstance()->get_udpSocket();
        // this->udpSocket->bind(17070);
        int port = 7070;
        QTimer *checkCancel_t = new QTimer(this);
        QString hdinfo, serial_number;
        hdinfo = get_encrypted_hardware_info();
        serial_number = get_serial_number();

        QSettings settings("/etc/kylin-activation/activation_conf.ini", QSettings::IniFormat);
        QString serveDns = settings.value("KMS_Activation/ServerIp").toString();
        QString udpSendInfo = "KY-DEACTIVATE-CHECK:" + serial_number + ":" + hdinfo;

        checkCancel_t->start(200);

        if(!m_deactivateWid->server_dns.isEmpty()) {
            serveDns = m_deactivateWid->server_dns;
        }
        if(!serveDns.isEmpty()) {
            this->udpSocket->writeDatagram(udpSendInfo.toLatin1(),udpSendInfo.length(),QHostAddress(serveDns),port);
        } else {
            this->udpSocket->writeDatagram(udpSendInfo.toLatin1(),udpSendInfo.length(),QHostAddress::Broadcast,port);
        }
        qDebug()<<"udp send:"<<udpSendInfo;
        connect(this->udpSocket,&QUdpSocket::readyRead,this,[=]
        {
            char buf[1024]={0};
            quint16 report;
            QHostAddress serverip;
            qint64 len = this->udpSocket->readDatagram(buf,sizeof(buf),&serverip,&report);
            qDebug()<<"udp recv:"<<QString::fromLocal8Bit(buf);
            if(len>0) {
                QStringList list=QString::fromLocal8Bit(buf).split(":");
                if(list.at(0)=="KY-DEACTIVATE-QUOTA" && list.size()==2) {
                    QString quota=list.at(1);
                    switch (quota.toInt()) {
                    case -1:
                        deactivate_label->setVisible(false);
                        break;
                    default:
                        deactivate_label->setVisible(true);
                        break;
                    }
                    m_deactivateWid->getServerInfo(quota.toInt(),serverip);
                    if (checkCancel_t->isActive())
                        checkCancel_t->stop();
                }
            }
            disconnect(this->udpSocket,&QUdpSocket::readyRead,this,0);
        });

        connect(checkCancel_t,&QTimer::timeout,this,[=]() {
            static int checkCount = 0;

            qDebug()<<"udp send:"<<udpSendInfo;
            if(!serveDns.isEmpty()) {
                this->udpSocket->writeDatagram(udpSendInfo.toLatin1(),udpSendInfo.length(),QHostAddress(serveDns),port);
            } else {
                this->udpSocket->writeDatagram(udpSendInfo.toLatin1(),udpSendInfo.length(),QHostAddress::Broadcast,port);
            }
            checkCount++;
            if (checkCount>=5) {
                if (checkCancel_t->isActive())
                    checkCancel_t->stop();
                qDebug()<<"Unable to check if activation can be cancelled.";
            }
        });
    } else {
        qDebug()<<"Currently not activated, or activation has expired"; //当前未激活，或激活已过期
    }
}

void SystemActivationMainWindow::send_activation_info(QString info)
{
    qDebug("Start sending info!");
    QUrl Url ;
    QString config_path = QDir::homePath() + "/.config/activation_conf.ini";
    QFileInfo file(config_path);
    QString rename = "cp " + config_path + " " + config_path + ".bak";

    char * ch;
    QByteArray ba = rename.toLatin1();
    ch=ba.data();
    if(file.exists()==true)
        system(ch);

    Url.setUrl("https://wx.kylinos.cn/api/upload_hwinfo/v1");
    QByteArray sendData = info.toLocal8Bit();

    QNetworkRequest request = QNetworkRequest(Url);
    request.setRawHeader("Accept", "*/*");
    request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9");
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    request.setRawHeader("X-Requested-With:", "XMLHttpRequest");
    m_accessManager_Registered->post(request, sendData);
}

int SystemActivationMainWindow::finishedSlot_info(QNetworkReply *registered)
{
    QString config_path = QDir::homePath() + "/.config/activation_conf.ini";
    QString bak_path = config_path + ".bak";
    QFileInfo file(bak_path);
    QString rename = "cp " + bak_path + " "  + config_path;

    char * ch;
    QByteArray ba = rename.toLatin1();
    ch=ba.data();

    qDebug()<<"finish sending info!";
    if (registered->error() == QNetworkReply::NoError)
    {
        // 获取响应信息
        QByteArray bytes = registered->readAll();      //读取所有字节；

        QJsonParseError jsonError;
        //转化为JSON文档
        QJsonDocument doucment = QJsonDocument::fromJson(bytes, &jsonError);
        // 解析Json  error
        if (doucment.isObject()) {
            QJsonObject obj = doucment.object();

            QJsonValue val;
            if (obj.contains("errcode")) {
                val = obj.value("errcode");
                if(val.toInt() == 0){
                    qDebug() << "send info success!";
                    if(file.exists()==true)
                        system(ch);
                    return 0;
                }
                else{
                    qDebug() << "send info error:"<<obj.value("errcode").toString();
                    return val.toString().toInt();
                }
            }

        }
        if (jsonError.error != QJsonParseError::NoError) {
            qDebug() << QStringLiteral("解析Json失败");
            return 101;
        }
    }
    else
    {
        qDebug()<<"handle errors here!";
        QVariant statusCodeV = registered->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
        return 102;
    }
    registered->deleteLater();
}

void SystemActivationMainWindow::slotMessageReceived(const QString&message) {
    qDebug() << message;
    KWindowSystem::forceActiveWindow(this->winId());
    this->show();
}
